﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using SheepClock.CustomUIComponents;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;
using Microsoft.Phone.Scheduler;

namespace SheepClock
{
    public partial class AlarmsPage : PhoneApplicationPage
    {
        private string alarmsFilename = "alarms.txt";

        private bool mAlarmsLoaded = false;

        public AlarmsPage()
        {
            InitializeComponent();
            mAlarmsLoaded = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isf.FileExists(alarmsFilename))
                {
                    if (!mAlarmsLoaded)
                    {
                        FillListWithAlarms();
                        mAlarmsLoaded = true;
                    }
                }
                else
                {
                    IsolatedStorageFileStream isfs = isf.CreateFile(alarmsFilename);
                    isfs.Close();
                    isfs.Dispose();
                }
            }

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            SaveAlarms();

            base.OnNavigatedFrom(e);
        }

        private void FillListWithAlarms()
        {
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            using (StreamReader sr = new StreamReader(myIsolatedStorage.OpenFile(alarmsFilename, FileMode.Open, FileAccess.Read)))
            {
                string line = sr.ReadLine();
                int index = 0;
                while (line != null && !string.IsNullOrEmpty(line))
                {
                    MyAlarm alarm = new MyAlarm(line.Trim());
                    AlarmListItem item = new AlarmListItem();
                    item.Index = index++;
                    item.AlarmID = alarm.ID;
                    item.myAlarmItem.AlarmTime.Text = "@" + alarm.Hours.ToString("00") + ":" + alarm.Minutes.ToString("00");
                    item.mySettingsItem.hourTextBox.Text = alarm.Hours.ToString("00");
                    item.mySettingsItem.minuteTextBox.Text = alarm.Minutes.ToString("00");
                    item.myAlarmItem.AlarmName.Text = alarm.Name;
                    item.mySettingsItem.NameTextBox.Text = alarm.Name;
                    item.myAlarmItem.AlarmSwitch.IsON = alarm.IsON;
                    item.DeleteTapped += new EventHandler(item_DeleteTapped);
                    AlarmsStack.Children.Add(item);

                    line = sr.ReadLine();
                }
            }
        }

        private void SaveAlarms()
        {
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            using (StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(alarmsFilename, FileMode.Truncate, FileAccess.Write, myIsolatedStorage)))
            {
                for (int i = 0; i < AlarmsStack.Children.Count; i++)
                {
                    AlarmListItem item = AlarmsStack.Children[i] as AlarmListItem;
                    MyAlarm alarm = new MyAlarm();
                    alarm.ID = item.AlarmID;
                    alarm.Name = item.myAlarmItem.AlarmName.Text;
                    alarm.Hours = Convert.ToInt32(item.myAlarmItem.AlarmTime.Text.Substring(1).Split(':')[0]);
                    alarm.Minutes = Convert.ToInt32(item.myAlarmItem.AlarmTime.Text.Substring(1).Split(':')[1]);
                    alarm.IsON = item.myAlarmItem.AlarmSwitch.IsON;
                    sw.WriteLine(alarm.ToString());
                }
            }
        }



        private void AddButton_Click(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now.AddMinutes(10);
            AlarmListItem item = new AlarmListItem();
            item.Index = AlarmsStack.Children.Count;
            item.AlarmID = Guid.NewGuid().ToString();
            item.myAlarmItem.AlarmTime.Text = "@" + now.ToString("HH:mm");
            item.mySettingsItem.hourTextBox.Text = now.Hour.ToString("00");
            item.mySettingsItem.minuteTextBox.Text = now.Minute.ToString("00");
            item.myAlarmItem.AlarmName.Text = "Alarm" + (AlarmsStack.Children.Count + 1);
            item.mySettingsItem.NameTextBox.Text = "Alarm" + (AlarmsStack.Children.Count + 1);
            item.myAlarmItem.AlarmSwitch.IsON = true;
            item.SetAlarmON();
            item.DeleteTapped += new EventHandler(item_DeleteTapped);
            AlarmsStack.Children.Add(item);
        }

        private void ClearAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("All your alarms will be deleted.", "Clear all", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                for (int i = 0; i < AlarmsStack.Children.Count; i++)
                {
                    string alarmID = (AlarmsStack.Children[i] as AlarmListItem).AlarmID;
                    if (alarmID != null)
                    {
                        if (ScheduledActionService.Find(alarmID) != null)
                            ScheduledActionService.Remove(alarmID);
                    }
                }
                AlarmsStack.Children.Clear();
            }
        }

        void item_DeleteTapped(object sender, EventArgs e)
        {
            string alarmName = (sender as AlarmListItem).myAlarmItem.AlarmName.Text;
            int index = (sender as AlarmListItem).Index;
            if (MessageBox.Show("Are you sure you want to delete " + alarmName, alarmName, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                AlarmsStack.Children.RemoveAt(index);
                for (int i = 0; i < AlarmsStack.Children.Count; i++)
                    (AlarmsStack.Children[i] as AlarmListItem).Index = i;
            }
        }

    }
}